<template>
  <div class="file-center">
    <el-row :gutter="20">
      <el-col :span="16">
        <el-card class="upload-card">
          <template #header>
            <div class="card-header">
              <span>文件上传</span>
            </div>
          </template>

          <el-tabs v-model="activeTab" @tab-change="handleTabChange">
            <el-tab-pane label="通用上传" name="general">
              <el-form
                ref="generalFormRef"
                :model="generalForm"
                :rules="generalRules"
                label-width="100px"
              >
                <el-form-item label="文件分类" prop="category">
                  <el-select
                    v-model="generalForm.category"
                    placeholder="请选择文件分类"
                    style="width: 100%"
                  >
                    <el-option label="头像" value="AVATAR" />
                    <el-option label="证书" value="CERTIFICATE" />
                    <el-option label="训练照片" value="TRAINING" />
                    <el-option label="课程" value="COURSE" />
                    <el-option label="公告" value="ANNOUNCEMENT" />
                    <el-option label="其他" value="OTHER" />
                  </el-select>
                </el-form-item>

                <el-form-item label="文件" prop="fileList">
                  <el-upload
                    v-model:file-list="generalForm.fileList"
                    class="upload-demo"
                    drag
                    :auto-upload="false"
                    :limit="10"
                    multiple
                  >
                    <el-icon class="el-icon--upload">
                      <UploadFilled />
                    </el-icon>
                    <div class="el-upload__text">
                      将文件拖到此处，或<em>点击上传</em>
                    </div>
                    <template #tip>
                      <div class="el-upload__tip">
                        支持上传图片、文档等文件，单次最多上传10个文件
                      </div>
                    </template>
                  </el-upload>
                </el-form-item>

                <el-form-item label="是否公开" prop="isPublic">
                  <el-switch v-model="generalForm.isPublic" />
                </el-form-item>

                <el-form-item>
                  <el-button
                    type="primary"
                    @click="submitGeneralUpload"
                    :loading="uploadLoading"
                  >
                    上传文件
                  </el-button>
                  <el-button @click="resetGeneralForm">重置</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>

            <el-tab-pane label="头像上传" name="avatar">
              <el-form
                ref="avatarFormRef"
                :model="avatarForm"
                :rules="avatarRules"
                label-width="100px"
              >
                <el-form-item label="头像图片" prop="file">
                  <el-upload
                    class="avatar-uploader"
                    :show-file-list="false"
                    :auto-upload="false"
                    :on-change="handleAvatarChange"
                  >
                    <img
                      v-if="avatarForm.imageUrl"
                      :src="avatarForm.imageUrl"
                      class="avatar"
                    />
                    <el-icon v-else class="avatar-uploader-icon">
                      <Plus />
                    </el-icon>
                  </el-upload>
                </el-form-item>

                <el-form-item label="预览" v-if="avatarForm.imageUrl">
                  <div class="avatar-preview">
                    <img :src="avatarForm.imageUrl" class="preview-image" />
                  </div>
                </el-form-item>

                <el-form-item>
                  <el-button
                    type="primary"
                    @click="submitAvatarUpload"
                    :loading="uploadLoading"
                  >
                    上传头像
                  </el-button>
                  <el-button @click="resetAvatarForm">重置</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-col>

      <el-col :span="8">
        <el-card class="stats-card">
          <template #header>
            <div class="card-header">
              <span>文件统计</span>
            </div>
          </template>

          <div class="stats-content">
            <el-row :gutter="20">
              <el-col :span="12">
                <div class="stat-item">
                  <div class="stat-icon" style="background-color: #409eff;">
                    <el-icon><Picture /></el-icon>
                  </div>
                  <div class="stat-info">
                    <div class="stat-value">{{ stats.imageCount }}</div>
                    <div class="stat-label">图片</div>
                  </div>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="stat-item">
                  <div class="stat-icon" style="background-color: #67c23a;">
                    <el-icon><Document /></el-icon>
                  </div>
                  <div class="stat-info">
                    <div class="stat-value">{{ stats.documentCount }}</div>
                    <div class="stat-label">文档</div>
                  </div>
                </div>
              </el-col>
            </el-row>

            <div class="category-stats">
              <div class="category-item">
                <span>头像</span>
                <span>{{ stats.avatarCount }}</span>
              </div>
              <div class="category-item">
                <span>证书</span>
                <span>{{ stats.certificateCount }}</span>
              </div>
              <div class="category-item">
                <span>训练照片</span>
                <span>{{ stats.trainingCount }}</span>
              </div>
              <div class="category-item">
                <span>课程</span>
                <span>{{ stats.courseCount }}</span>
              </div>
            </div>
          </div>
        </el-card>

        <el-card class="quick-actions">
          <template #header>
            <div class="card-header">
              <span>快捷操作</span>
            </div>
          </template>

          <div class="actions-grid">
            <div class="action-item" @click="goToFileList('AVATAR')">
              <div class="item-icon" style="background-color: #409eff;">
                <el-icon><User /></el-icon>
              </div>
              <div class="item-label">头像管理</div>
            </div>
            <div class="action-item" @click="goToFileList('TRAINING')">
              <div class="item-icon" style="background-color: #67c23a;">
                <el-icon><Camera /></el-icon>
              </div>
              <div class="item-label">训练照片</div>
            </div>
            <div class="action-item" @click="goToFileList('CERTIFICATE')">
              <div class="item-icon" style="background-color: #e6a23c;">
                <el-icon><Medal /></el-icon>
              </div>
              <div class="item-label">证书管理</div>
            </div>
            <div class="action-item" @click="goToFileList('ALL')">
              <div class="item-icon" style="background-color: #f56c6c;">
                <el-icon><Folder /></el-icon>
              </div>
              <div class="item-label">全部文件</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import type { UploadFile, UploadUserFile } from 'element-plus'
import { fileApi, avatarApi } from '@/api/modules/file'
import type { UploadFileRequest } from '@/types/api/file'
import { preventDuplicateSubmit } from '@/utils'

// 当前激活的标签页
const activeTab = ref('general')

// 通用上传表单
const generalFormRef = ref()
const generalForm = reactive({
  category: 'OTHER',
  fileList: [] as UploadUserFile[],
  isPublic: true
})

// 头像上传表单
const avatarFormRef = ref()
const avatarForm = reactive({
  file: null as File | null,
  imageUrl: ''
})

// 上传状态
const uploadLoading = ref(false)

// 文件统计
const stats = reactive({
  imageCount: 125,
  documentCount: 28,
  avatarCount: 45,
  certificateCount: 12,
  trainingCount: 68,
  courseCount: 22
})

// 表单验证规则
const generalRules = {
  category: [
    { required: true, message: '请选择文件分类', trigger: 'change' }
  ],
  fileList: [
    { required: true, message: '请上传文件', trigger: 'change' }
  ]
}

const avatarRules = {
  file: [
    { required: true, message: '请上传头像图片', trigger: 'change' }
  ]
}

// 标签页切换
const handleTabChange = (name: string) => {
  activeTab.value = name
}

// 处理头像文件变化
const handleAvatarChange = (uploadFile: UploadFile) => {
  if (uploadFile.raw) {
    avatarForm.file = uploadFile.raw
    avatarForm.imageUrl = URL.createObjectURL(uploadFile.raw)
  }
}

// 重置通用表单
const resetGeneralForm = () => {
  generalForm.category = 'OTHER'
  generalForm.fileList = []
  generalForm.isPublic = true
}

// 重置头像表单
const resetAvatarForm = () => {
  avatarForm.file = null
  avatarForm.imageUrl = ''
}

// 提交头像上传
const submitAvatarUpload = async () => {
  if (!avatarFormRef.value) return

  try {
    await avatarFormRef.value.validate()

    if (!avatarForm.file) {
      ElMessage.warning('请上传头像图片')
      return
    }

    // 使用防重复提交保护
    await preventDuplicateSubmit('upload_avatar', async () => {
      uploadLoading.value = true

      try {
        const res = await avatarApi.uploadAvatar(avatarForm.file!)
        ElMessage.success('头像上传成功')

        // 重置表单
        resetAvatarForm()
      } catch (error: any) {
        ElMessage.error('头像上传失败')
        throw error // 重新抛出错误以确保防重复提交正确处理
      } finally {
        uploadLoading.value = false
      }
    })
  } catch (error: any) {
    // 防重复提交保护捕获的错误
    if (error.message === '请勿重复提交') {
      ElMessage.warning('请勿重复提交')
    }
  }
}

// 提交通用上传
const submitGeneralUpload = async () => {
  if (!generalFormRef.value) return

  try {
    await generalFormRef.value.validate()

    if (generalForm.fileList.length === 0) {
      ElMessage.warning('请至少上传一个文件')
      return
    }

    // 使用防重复提交保护
    await preventDuplicateSubmit('upload_general_files', async () => {
      uploadLoading.value = true

      try {
        // 处理文件上传
        for (const file of generalForm.fileList) {
          if (file.raw) {
            const uploadData: UploadFileRequest = {
              file: file.raw,
              category: generalForm.category as any,
              isPublic: generalForm.isPublic
            }
            await fileApi.uploadFile(uploadData)
          }
        }

        ElMessage.success('文件上传成功')
        resetGeneralForm()
      } catch (error: any) {
        ElMessage.error('文件上传失败')
        throw error // 重新抛出错误以确保防重复提交正确处理
      } finally {
        uploadLoading.value = false
      }
    })
  } catch (error: any) {
    // 防重复提交保护捕获的错误
    if (error.message === '请勿重复提交') {
      ElMessage.warning('请勿重复提交')
    }
  }
}

// 跳转到文件列表
const goToFileList = (category: string) => {
  // 这里可以跳转到对应的文件列表页面
  ElMessage.info(`跳转到${category === 'ALL' ? '全部文件' : category}列表`)
}

// 生命周期
onMounted(() => {
  // 可以在这里加载统计数据
})
</script>

<style scoped>
.file-center {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.upload-card {
  margin-bottom: 20px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-preview {
  text-align: center;
}

.preview-image {
  max-width: 100%;
  max-height: 300px;
  border-radius: 4px;
}

.stats-content {
  padding: 20px 0;
}

.stat-item {
  display: flex;
  align-items: center;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 8px;
  margin-bottom: 15px;
}

.stat-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
}

.stat-icon .el-icon {
  font-size: 20px;
  color: white;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.category-stats {
  margin-top: 20px;
}

.category-item {
  display: flex;
  justify-content: space-between;
  padding: 10px 0;
  border-bottom: 1px solid #ebeef5;
}

.category-item:last-child {
  border-bottom: none;
}

.actions-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
}

.action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.action-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.action-item .item-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 10px;
}

.action-item .item-icon .el-icon {
  font-size: 20px;
  color: white;
}

.action-item .item-label {
  font-size: 14px;
  color: #606266;
}
</style>
